package com.athay.diary.controller;

import com.athay.diary.dto.request.DiaryEditDTO;
import com.athay.diary.dto.response.CommonResult;
import com.athay.diary.entity.Diary;
import com.athay.diary.service.DiaryService;
import com.athay.diary.util.SecurityUtils;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/diary")
public class DiaryController {

    private final DiaryService diaryService;

    public DiaryController(DiaryService diaryService) {
        this.diaryService = diaryService;
    }

    // 创建日记
    @PostMapping("/create")
    public CommonResult create(@RequestBody DiaryEditDTO diaryDTO, Authentication authentication) {
        Diary diary = new Diary();
        diary.setTitle(diaryDTO.getTitle());
        diary.setContent(diaryDTO.getContent());
        diary.setUserId(SecurityUtils.getCurrentUser(authentication).getId());
        diary.setCreateTime(new Date());
        diary.setUpdateTime(new Date());
        diaryService.save(diary);
        return CommonResult.success("日记创建成功");
    }

    // 获取当前用户的日记列表
    @GetMapping("/list")
    public CommonResult<List<Diary>> list(Authentication authentication) {
        List<Diary> diaries = diaryService.listByCurrentUser(authentication);
        return CommonResult.success(diaries);
    }

    // 更新日记
    @PutMapping("/update/{id}")
    public CommonResult update(
        @PathVariable Long id,
        @RequestBody DiaryEditDTO diaryDTO,
        Authentication authentication
    ) {
        Diary diary = new Diary();
        diary.setId(id);
        diary.setTitle(diaryDTO.getTitle());
        diary.setContent(diaryDTO.getContent());
        diaryService.update(diary, authentication);
        return CommonResult.success("日记更新成功");
    }

    // 删除日记
    @DeleteMapping("/delete/{id}")
    public CommonResult delete(
        @PathVariable Long id,
        Authentication authentication
    ) {
        diaryService.deleteById(id, authentication);
        return CommonResult.success("日记删除成功");
    }
}